<?php declare(strict_types=1);
namespace app\logic;

use app\exception\auth\TokenRequired;
use app\facade\model\UserToken as FaUserTokenModel;
use app\library\DefaultConfig;
use app\model\UserToken as UserTokenModel;
use think\facade\Session;
use think\Request;

class Base {

    /**
     * @var Request
     */
    protected $request;

    protected $userId;

    protected $isSuper;

    public function __construct(Request $request)
    {
        $this->request = $this->request == null ? $request : $this->request;
        // Get Header Token
        $token = $request->header(DefaultConfig::HEADER_TOKEN_NAME,'');
        // Get User ID By Token
        if(!empty($token)){
            $this->setUserID($token);
        }
        $this->setIsSuper();
    }



    // Set User ID
    protected function setUserID(string $token) : void
    {
        // Check Token
        $token = $this->getTokenByToken($token);
        // Set User ID
        $this->userId = $token['user_id'];
    }

    protected function setIsSuper(){
        $this->isSuper = $this->userId  == 1 ? true : false;
    }

    // 其它地方有用到所在用Public
    public function getTokenByToken(string  $token): ?UserTokenModel {
        // Token Required
        if (empty($token)) throw new TokenRequired();
        // Check Token
        $token = FaUserTokenModel::getTokenByToken($token);

        return $token;
    }
}
